package com.shdanyan.security;

import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@Component
public final class JwtTokenHandler {

	private final String secret;
	private final CustomUserDetailsService userInfoService;

	@Autowired
	public JwtTokenHandler(@Value("${web.shdanyan.jwt.secret}") String secret,
			CustomUserDetailsService userInfoService) {
		this.secret = secret;
		this.userInfoService = userInfoService;
	}

	Optional<UserDetails> parseUserFromToken(String token) {
		String username = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().getSubject();
		return Optional.ofNullable(userInfoService.loadUserByUsername(username));
	}

	public String createTokenForUser(UserDetails user) {
		final ZonedDateTime afterOneWeek = ZonedDateTime.now().plusWeeks(1);
		return Jwts.builder().setSubject(user.getUsername()).signWith(SignatureAlgorithm.HS512, secret)
				.setExpiration(Date.from(afterOneWeek.toInstant())).compact();
	}
}